package com.ziyucoding.springboot.labs.lab8.skywalking.esjestdemo.controller;

import com.ziyucoding.springboot.labs.lab8.skywalking.esjestdemo.dataobject.ESUserDO;
import com.ziyucoding.springboot.labs.lab8.skywalking.esjestdemo.repository.ESUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ziyucoding
 * @date 2022-10-31
 **/
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private ESUserRepository userRepository;

    @GetMapping("/elasticsearch")
    public Map<String, Object> elasticsearch() {
        this.save(1);

        ESUserDO userDO = this.findById(1);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "成功");

        Map<String, Object> data = new HashMap<>();
        data.put("id", userDO.getId());
        data.put("userName", userDO.getUserName());

        result.put("data", data);
        return result;
    }

    /**
     * 保存
     *
     * @param id
     * @return void
     **/
    public void save(Integer id) {
        ESUserDO user = new ESUserDO();
        user.setId(id);
        user.setUserName("userName：" + id);
        user.setPwd("pwd：" + id);
        user.setCreateTime(new Date());
        userRepository.save(user);
    }

    /**
     * 查询
     *
     * @param id
     * @return ESUserDO
     **/
    public ESUserDO findById(Integer id) {
        return userRepository.findById(id).orElse(null);
    }

}
